package com.you07.learn.controller;

import com.alibaba.fastjson.JSONObject;
import com.you07.learn.entity.UserEntity;
import com.you07.learn.service.UserServiceI;
import com.you07.learn.utils.Result;
import com.you07.learn.utils.ResultMessage;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.List;

/**
 * @author chenguo
 * @version 1.0
 * @explain${EXPLAIN}
 * @create 2019年01月30日 23时:48分
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceI userService;

    /**
     * 保存用户
     *
     * @param userEntity
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/v1/save")
    @ResponseBody
    public ResultMessage<?> save(UserEntity userEntity) throws InvocationTargetException, IllegalAccessException {
        JSONObject result = new JSONObject();
        UserEntity user = new UserEntity();
        user.setUserName(userEntity.getUserName());
        user.setRealName(userEntity.getRealName());
        BeanUtils.copyProperties(user, userEntity);
        userService.save(user);
        return Result.success(user);
    }

    /**
     * 获取全部用户信息
     *
     * @return
     */
    @RequestMapping(value = "/v1/list")
    @ResponseBody
    public ResultMessage<?> list() {
        List<UserEntity> list = userService.list();
        return Result.success(list);
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/v1/find/{id}")
    @ResponseBody
    public ResultMessage<?> findById(@PathVariable BigInteger id) {
        UserEntity user = userService.findById(id);
        return Result.success(user);
    }
}
